package com.example.demo.Control;

import com.example.demo.Common.AjaxResult;
import com.example.demo.Common.PasswordTools;
import com.example.demo.Common.PublicValue;
import com.example.demo.Common.UserSessionTools;
import com.example.demo.Entity.Userinfo;
import com.example.demo.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserControl {
  @Autowired
    public UserService userService;

  @RequestMapping("/sign")
    public AjaxResult reg(Userinfo userinfo) {
    //进行非空判断
    //StringUtils.hasLength
    //如果字符序列不为 null 值,并且字符序列的长度大于 0 ,则返回 true.
    if (userinfo == null || !StringUtils.hasLength(userinfo.getUsername())
            || !StringUtils.hasLength(userinfo.getPassword())) {
      return AjaxResult.fail(-1, "参数有误");
    }
    Userinfo user=userService.login(userinfo.getUsername());
    if(user!=null){
      return  AjaxResult.fail(-1,"用户名重复");
    }
    String password= PasswordTools.encrypt(userinfo.getPassword());
    userinfo.setPassword(password);
    int result= userService.reg(userinfo);
    return AjaxResult.success(result);
  }
  @RequestMapping("/login")
  public AjaxResult login(String username, String password, HttpServletRequest req){
   //进行非空判断
    if(!StringUtils.hasLength(username)||!StringUtils.hasLength(password)){
      return AjaxResult.fail(-1,"参数缺失");
    }
    Userinfo userinfo= userService.login(username);
    if(userinfo==null||userinfo.getId()<=0){
      return AjaxResult.fail(-2,"用户名或密码错误");
    }

    if(!PasswordTools.decrypt(password,userinfo.getPassword())){
      return AjaxResult.fail(-2,"用户名或密码错误");
    }
    //将登录信息保存到session会话中
    HttpSession session=req.getSession();
    session.setAttribute(PublicValue.SessionValue,userinfo);
    return AjaxResult.success(1);
  }
  @RequestMapping("/logout")
  public AjaxResult logout(HttpServletRequest req){
    HttpSession session=req.getSession();
   // System.out.println(PublicValue.SessionValue);
    session.removeAttribute(PublicValue.SessionValue);
    return AjaxResult.success(1);
  }
  @RequestMapping("/islogin")
  public  AjaxResult islogin(HttpServletRequest req){
   Userinfo userinfo=UserSessionTools.getLoginUser(req);
   if(userinfo==null||userinfo.id<=0){
     return AjaxResult.fail(-1,"未登录");
   }
    return AjaxResult.success(1);
  }
  @RequestMapping("/author")
  public  AjaxResult getauthor(HttpServletRequest req){
    Userinfo userinfo=UserSessionTools.getLoginUser(req);
    return AjaxResult.success(userinfo);
  }
  
}
